﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnchorManager : MonoBehaviour
{
    private Camera mainCamera;
    private GameObject anchorGo;
    private bool turnOnGenAnchorFun = false;
    private Dictionary<string, Anchor> allAnchorDict;

    public static AnchorManager Instance;
    private LineRenderer lr;
    public Dictionary<string, Anchor> AllAnchorDict { get => allAnchorDict; set => allAnchorDict = value; }

    private void Awake()
    {
        Instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        mainCamera = RTEditor.EditorCamera.Instance.gameObject.GetComponent<Camera>();
        anchorGo = Resources.Load("Anchor") as GameObject;
        allAnchorDict = new Dictionary<string, Anchor>();
        lr = GetComponent<LineRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        if (turnOnGenAnchorFun && Input.GetMouseButtonDown(0))
        {
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                GameObject go1 = Instantiate(anchorGo, hit.point, default);
                go1.transform.SetParent(transform);
                Anchor anchor = go1.GetComponent<Anchor>();
                anchor.ID = GenerateIDManager.GenerateID();
                go1.name = "Anchor" + anchor.ID.ToString();
                allAnchorDict.Add(go1.name, anchor);
                //TODO 使用GF
            }
        }
    }

    /// <summary>
    /// 开启锚点生成功能
    /// </summary>
    /// <param name="isOn"></param>
    public void OpenGenAnchorFunc(bool isOn)
    {
        turnOnGenAnchorFun = isOn;
    }

    /// <summary>
    /// 绘制锚点区域
    /// </summary>
    /// <param name="vertices"></param>
    public void DrawAnchorGroupArea(List<Transform> vertices)
    {
        Vector3[] positions = new Vector3[vertices.Count];
        for (int i = 0; i < vertices.Count; i++)
        {
            positions[i] = vertices[i].position;
        }
        lr.positionCount = vertices.Count;
        lr.SetPositions(positions);
    }

    public void DrawAnchorGroupArea(List<Anchor> anchors)
    {
        Vector3 offset = Vector3.up * 0.4f; //绘制的线框高于锚点，不与地面重合
        Vector3[] positions = new Vector3[anchors.Count];
        for (int i = 0; i < anchors.Count; i++)
        {
            positions[i] = anchors[i].Position + offset;
        }
        lr.positionCount = anchors.Count;
        lr.SetPositions(positions);
    }
}
